//
//  CMyOrderVC.m
//  ProjectforHDX
//
//  Created by yinda on 16/8/8.
//  Copyright © 2016年 H.DX. All rights reserved.
//

#import "CMyOrderVC.h"
#import "MainHandleTableCell.h"
#import "SearchBar.h"
#import "CMyOrderSearchVC.h"
#import "CSMyOrderConfirmingTVC.h"
#import "OrderDetailsVC.h"



@interface CMyOrderVC ()<UITableViewDataSource,UITableViewDelegate>
{
    BOOL isMJRefresh;
}

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *tableArray;


@property (nonatomic, strong) SearchBar *searchBarTop;

@end

@implementation CMyOrderVC
static NSString *mainTableCell_ID = @"mainHandleTableCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableArray=[[NSMutableArray alloc] initWithCapacity:0];
    [self requestData];
    [self setupView];
}

-(void)setupView {
    
    isMJRefresh = YES;

    self.navColor = SYSTEM_COLOR;
    // 我的消息
    self.labnav.text= [UtilCheck language:@"setting.order"];
    [self.labnav setFont:NavFontSize];
    [self.labnav setTextColor:[UIColor whiteColor]];
    
    // view
    self.mBackColor =[UIColor groupTableViewBackgroundColor];
    
    //searchbar
    UISearchBar *searchBar = [[UISearchBar alloc]init];
    searchBar.frame = CGRectMake(0, 0, SCREEN_WIDTH, 40);
    searchBar.placeholder =[UtilCheck language:@"customer.search"];
    [searchBar setImage:BDFILEIMAGENAEM(@"default/img_search") forSearchBarIcon:(UISearchBarIconSearch) state:(UIControlStateNormal)];
    [self.view addSubview:searchBar];
     UIButton *btn = [[UIButton alloc]init];
    btn.frame = searchBar.frame;
    [self.view addSubview:btn];
    [btn addTarget:self action:@selector(searchOrder) forControlEvents:UIControlEventTouchUpInside];
    searchBar.backgroundImage = [self imageWithColor:[UtilCheck hexStringToColor:@"eeeeee" alpha:1.0] size:searchBar.bounds.size];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, SCREEN_HEIGHT-62) style:(UITableViewStyleGrouped)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle =NO;
    [self.tableView registerNib:[UINib nibWithNibName:@"MessageCell" bundle:nil]
         forCellReuseIdentifier:@"MessageCell"];
    [self addHeader];
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = [UtilCheck hexStringToColor:@"f7f7f7" alpha:1.0];
    
//    
//    if (self.type == 4) {
//        [Toolobject showAlterwithMessage:@"待返还故障件订单列表"];
//    }
}

-(void)searchOrder
{
    CMyOrderSearchVC *vc = [[CMyOrderSearchVC alloc]init];
    vc.fatherVC = self;
    vc.type = [NSString stringWithFormat:@"%ld", (long)self.type];
    [self presentViewController:vc animated:UIModalTransitionStyleFlipHorizontal completion:^{
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


#pragma -mark delegate an datasource
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.tableArray.count;
}


#define CELL_HEIGHT 115

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    OrderModel *orderModel=[self.tableArray objectAtIndex:indexPath.row];
    CGFloat cellHeight;
    if (orderModel.customer.length >15) {
        cellHeight = CELL_HEIGHT + 15;
    }
    else {
        cellHeight = CELL_HEIGHT;
    }
    if(orderModel.open){
        MainHandleTableCell *cell= [[MainHandleTableCell alloc] init];
        CGFloat heigt= cellHeight +[cell createStepView:orderModel].height;
        return heigt;
    }
    else{
        return cellHeight;
    }
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MainHandleTableCell *cell = (MainHandleTableCell*)[tableView dequeueReusableCellWithIdentifier:@"MainHandleTableCell"];
    if(cell == nil)
    {
        cell = [[MainHandleTableCell alloc] init];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegateVC=self;
    cell.model=[self.tableArray objectAtIndex:indexPath.row];
    cell.Refesh=^(OrderModel* model){
        [self.tableArray setObject:model atIndexedSubscript:indexPath.row];
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    OrderModel *model = [self.tableArray objectAtIndex:indexPath.row];
    NSLog(@"订单类型是%@",model.type);
    
    if (model.orderType) {
        if ([model.orderType integerValue] > 2) {
            OrderDetailsVC *vc = [[OrderDetailsVC alloc]init];
            vc.orderCode = model.orderCode;
            [self.navigationController pushViewController:vc animated:YES];
            
        }else{
            CSMyOrderConfirmingTVC *view = [[CSMyOrderConfirmingTVC alloc]init];
            view.orderCode = model.orderCode;
            [self.navigationController pushViewController:view animated:YES];
        }
        
    }else{
        [Toolobject showTextWithMessage:@"服务器返回的订单类型不存在"];
    }

}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
    
    
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark- 网络请求
#pragma mark 添加下拉刷新
- (void)addHeader
{
    if(self.tableView.header==nil){
        __weak __typeof(self) weakSelf = self;
        // 添加上拉刷新头部控件
        self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            if(isMJRefresh){
                isMJRefresh=NO;
                // 进入刷新状态后会自动调用这个block
                [weakSelf requestData];
            }
        }];
        // 马上进入刷新状态
        [self.tableView.header beginRefreshing];
    }
    else
    {
        // 马上进入刷新状态
        [self.tableView.header beginRefreshing];
        
    }
}

/**
 *  获取首页订单数据
 */
-(void)requestData{
    [[BDHUD sharedManager] dismissHUD];
    [[BDHUD sharedManager] showBDHUD:self.view title:[THMangerTool language:@"HUD.title"]];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"page"] = @"1";
    params[@"size"] = @"100";
    params[@"type"] = @"0";
    if (self.type) {
        params[@"type"] = [NSString stringWithFormat:@"%ld",(long)self.type];
    }
    
    [AFHttpTool postJsonDatawithUrl:@"ordersStatistical" parameters:[params mutableCopy]
                                success:^(id responseObject) {
                                    isMJRefresh=YES;
                                    [self.tableView.header endRefreshing];
                                    [[BDHUD sharedManager] dismissHUD];
                                    if(1==[[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]){
                                        if([[responseObject objectForKey:@"data"] isKindOfClass:[NSArray class]]){
                                            NSArray *data=[responseObject objectForKey:@"data"];
                                            self.tableArray=[UtilCheck arraytoModel:data targetModel:@"OrderModel"];
                                            if(self.tableArray.count<1){
                                                [[BDHUD sharedManager] showNOneDataViewHUD:self.tableView top:60 title:[THMangerTool language:@"HUD.noOrderData"] onClick:^{
                                                    [self addHeader];
                                                }];
                                            }
                                            [self.tableView reloadData];
                                        }
                                        else{
                                            [self.tableArray removeAllObjects];
                                            if(self.tableArray.count<1){
                                                [[BDHUD sharedManager] showNOneDataViewHUD:self.tableView top:60 title:[THMangerTool language:@"HUD.noOrderData"] onClick:^{
                                                    [self addHeader];
                                                }];
                                            }
                                            [[BDHUD sharedManager] showWords:[THMangerTool language:@"HUD.nothing"]];
                                        }
                                    }
                                    else{
                                        //返回数据出问题 弹出服务器返回信息
                                        if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                                            [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
                                        }
                                        else{
                                            [[BDHUD sharedManager] showWords:[THMangerTool language:@"HUD.nothing"]];
                                        }
                                        [self.tableArray removeAllObjects];
                                        if(self.tableArray.count<1){
                                            [[BDHUD sharedManager] showNOneDataViewHUD:self.tableView top:60 title:[THMangerTool language:@"HUD.noOrderData"] onClick:^{
                                                [self addHeader];
                                            }];
                                        }
                                    }
                                } fail:^(id responseObject, NSError *error) {
                                    isMJRefresh=YES;
                                    [self.tableView.header endRefreshing];
                                    [[BDHUD sharedManager] dismissHUD];
                                    if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
                                        [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
                                    }else {
                                        [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
                                    }
                                    
                                    }];
}


//取消searchbar背景色
- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

@end

